<template>
	<div name="limiteSignIn">
        <div v-if="taskInfo">
            <van-nav-bar
                :title="navBarTaskText"
                left-arrow
                left-text="返回"
                fixed
                @click-left="$router.go(-1)"
            />
            <div v-if="!taskInfo.limited">
                <van-cell-group>
                    <van-cell center title="开始时间"  :value="this.taskInfo.createTime" />
                    <van-cell center title="计时"  :value="jishi" />                    
                </van-cell-group>
                <div style="margin: 20px;">
                    <van-button round type="info" @click="aKeySignInOver">结束签到</van-button>
                </div>
            </div>
            <div v-else>
                <van-cell-group>
                    <van-cell center title="开始时间"  :value="this.taskInfo.createTime" />
                    <van-cell center title="倒计时"  :value="daojishi" />                    
                </van-cell-group>
                <div style="margin: 20px;">
                    <van-button round type="info" @click="overSignIn">结束签到</van-button>
                </div>
            </div>
        </div>
        <div v-else> 
            <van-nav-bar
                :title="navBarTittle"
                left-arrow
                left-text="返回"
                fixed
                @click-left="$router.go(-1)"
            />
            <van-tabs @click="onChangeSignInType" >        
                <van-notice-bar
                left-icon="volume-o"
                :text="taskText"
                />
                        
                
                <van-tab title="一键签到">
                    <div style="margin: 10px;">
                            <van-dialog
                                title="请输入本次签到的经验值(1~100)"
                                v-model="showDiolog"
                                show-cancel-button
                                :beforeClose="beforeClose"
                            >
                                <van-field
                                    v-model="experience"                                    
                                    label="经验值"
                                    placeholder="请输入本次签到的经验值(1~100)"
                                    type="digit"
                                />				
                            </van-dialog>
                            <van-button round type="danger" @click="aKeySignIn">发起签到</van-button>                            
                    </div>
                    
                    
                </van-tab>
                <van-tab title="限时签到">
                    <van-dialog
                        v-model="showDiolog"
                        show-cancel-button
                        :beforeClose="beforeClose"
                        title="请输入本次签到的经验值(1~100)"
                    >
                        <van-field
                            v-model="experience"                       
                            label="经验值"
                            placeholder="请输入本次签到的经验值(1~100)"
                            type="digit"
                        />				
                    </van-dialog>
                    <van-popup  v-model="showTimePicker" round position="bottom">
                        <van-picker
                            title="请选择限时签到分钟数"
                            show-toolbar
                            :columns="columns"
                            @cancel="showTimePicker = false"
                            @confirm="onConfirm"
                        />
                    </van-popup>
                    
                    <van-count-down
                        ref="countDown"
                        millisecond
                        :time="currentTime"
                        :auto-start="false"
                        format="HH:mm:ss"
                        @finish="signInFinish"
                    />
                    <van-grid clickable :column-num="2">                    
                            <van-grid-item text="开始" icon="play-circle-o" @click="startSignIn" />
                            <van-grid-item text="设置签到时间" icon="replay" @click="setSignInTime" />                  
                    </van-grid>
                </van-tab>
                <!-- <van-tab title="手势签到">
                    
                </van-tab> -->
            </van-tabs>
        </div>
	</div>
</template>

<script>
    import {getLocation, longitude , latitude} from '@/api/gps.js';
    import { clockIn , taskOver  , viewTaskForTeacher , clockInTimeOut} from '@/api/signIn.js';
	import { Toast } from 'vant';
	export default {
        name: 'startSignIn',
		created() {
            this.detailBankeInfo = JSON.parse(localStorage.getItem('detailBankeInfo'));
            this.taskInfo = JSON.parse(localStorage.getItem('currentTask'));
            // this.viewTaskForT(this.detailBankeInfo.id);
            // viewTaskForTeacher(1,10,this.detailBankeInfo.id).then(res => {
            //     console.log(res);
            //     if(res.data.code === 0) {
            //         this.taskTotal = res.data.data.total;
            //         for(let r of res.data.data.records) {
            //             if(!r.ended) { // 如果课程没结束
            //                 console.log(r);
            //                 this.taskInfo = r;
            //                 break;
            //             }
            //         }
            //     }
            // }).catch(err => console.log(err));
            getLocation();
            if(this.taskInfo) // 有任务启动定时器
                this.sh = setInterval(()=>{
                    this.nowTimes = new Date().getTime() - Date.parse(this.taskInfo.createTime);               
                    this.overTime = (Date.parse(this.taskInfo.createTime) + this.taskInfo.timeout*1000) - new Date().getTime()
                },1000);
            
        },
		data() {
			return {
                sh: null,
                showDiolog: false,
                experience: -1,
                overTime: -1,
                nowTimes: '',
                taskInfo: {
                    // courseId: 1,
                    // createTime: "2021-06-18 10:25:48",
                    // createUser: 2,
                    // ended: true,
                    // id: 4,
                    // latitude: 26,
                    // longitude: 119,
                    // type: 3,
                    // updateTime: "2021-06-18 10:25:48",
                    // updateUser: 2
                },
                taskTotal: 20, // 任务数
                detailBankeInfo: {},
                startDisable: false,
				signInType: false, // 签到的方式  
                currentTime: 0,
				showTimePicker: false,
                columns: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],   // 用来选择限时签到的时间，单位：分钟
			}
		},
		computed: {
			navBarTittle() {
                return "发起签到" 
            },
            navBarTaskText() {
                if(!this.taskInfo.limited) {
                    return "一键签到";
                } else {
                    return "限时签到";
                }
            },
            taskText() {
                return '暂无签到信息'
            },
            jishi() {                
                return parseInt(this.nowTimes/1000/60)+':' + parseInt(this.nowTimes/1000%60);                
            },
            daojishi() {
                if(this.overTime<0) {
                    return '00:00'
                } else 
                return parseInt(this.overTime/1000/60)+':' + parseInt(this.overTime/1000%60);     
            }
		},
		methods: {
            beforeClose(action, done) {
                if(action === 'confirm') {
                    if(this.experience>0 && this.experience<=100) {
                        if(!this.signInType) {
                            let entity1 = {
                                "courseId": this.detailBankeInfo.id,
                                "latitude": latitude,
                                "longitude": longitude,  
                                "experience": this.experience,                
                            }                    
                            clockIn(entity1).then(res => {
                                // console.log(res);  
                                if(res.data.code === 0) {
                                    console.log('发布一键签到成功');
                                    this.sh = setInterval(()=>{
                                        this.nowTimes = new Date().getTime() - Date.parse(this.taskInfo.createTime);               
                                        this.overTime = (Date.parse(this.taskInfo.createTime) + this.taskInfo.timeout*1000) - new Date().getTime()
                                    },1000);            
                                    this.viewTaskForT(this.detailBankeInfo.id);
                                }
                                
                            }).catch(err => console.log(err));                    
                            
                        }
                        else {
                            const entity = {
                                "courseId": this.detailBankeInfo.id,
                                "latitude": latitude,
                                "longitude": longitude,
                                "experience": this.experience,
                                "timeout": this.currentTime / 1000
                            }
                            // console.log(entity);
                            clockInTimeOut(entity).then(res => {
                                if(res.data.code === 0) {
                                    console.log('发布限时签到成功');
                                    this.sh = setInterval(()=>{
                                        this.nowTimes = new Date().getTime() - Date.parse(this.taskInfo.createTime);               
                                        this.overTime = (Date.parse(this.taskInfo.createTime) + this.taskInfo.timeout*1000) - new Date().getTime()
                                    },1000);  
                                    this.viewTaskForT(this.detailBankeInfo.id);
                                    this.$refs.countDown.start();   
                                }                                                               
                            }).catch(err => console.log(err));
                        }
                    }
                        
                    else {
                        Toast('请输入0~100之间的数字');
                    }
                    done() //关闭
                    
                } else if(action === 'cancel') {
					done() //关闭
				}
            },
			onChangeSignInType(type) {  // 切换签到类型  ， 上方的那个tab用
                this.signInType = type ;                
            },
            onConfirm(val) {  // 时间选择器的确定按钮
                this.currentTime = val * 1000 * 60;                
                this.showTimePicker = false;
            },
            async startSignIn() {  //  限时签到的开始按钮的点击事件函数
                console.log(this.currentTime)
                if(this.taskInfo && !this.taskInfo.limited) {
                    Toast('有别的签到任务进行中，请勿重复操作！');
                } else if(this.taskInfo && this.taskInfo.limited) {
                    Toast('有限时签到任务进行中，请勿重复操作！');
                } else if(this.currentTime > 0) {
                    this.showDiolog = true;                    
                } else {
                    Toast('请先设置时间');
                } 
            },
            async overSignIn() { //  限时签到的结束按钮的点击事件函数
                this.currentTime = 0;  // ms
                if(this.taskInfo && !this.taskInfo.limited) {
                    Toast('有别的签到任务进行中，请勿错误操作！');
                } else if(this.taskInfo.limited) {
                    await taskOver(this.taskInfo.id).then(res => {
                        if(res.data.code === 0) {
                            console.log('限时签到结束'); 
                            this.taskInfo = null;    
                            clearInterval(this.sh); 
                        }                                                               
                    }).catch(err => console.log(err));
                    this.viewTaskForT(this.detailBankeInfo.id);
                }                
            },
            setSignInTime() { //  限时签到的设置签到时间点击事件函数
                if(this.taskInfo) {
                    Toast('有别的签到任务进行中，请勿重复操作！');
                } else {
                    this.$refs.countDown.reset();
                    this.showTimePicker = true;
                }
                
            },
            signInFinish() {  //  签到结束 时调用
                
                Toast('签到结束');
            },
            async aKeySignIn() { // 发起一键签到               
                this.showDiolog = true;
                
            },
            async aKeySignInOver() {
                
                if(this.taskInfo && this.taskInfo.limited) {
                    Toast('有别的签到任务进行中，请勿错误操作！');
                } else if(!this.taskInfo.limited) {
                    await taskOver(this.taskInfo.id).then(res => {
                        if(res.data.code === 0 ) {
                            console.log('一键签到结束');
                            clearInterval(this.sh); 
                            this.taskInfo = null;  
                        }                                               
                    }).catch(err => console.log(err));
                    this.viewTaskForT(this.detailBankeInfo.id);
                }
            },
            async viewTaskForT(courseId) {
                let curPage = 1;
                this.taskTotal = 20;
                // this.taskInfo = {
                //     // courseId: 1,
                //     // createTime: "2021-06-18 10:25:48",
                //     // createUser: 2,
                //     // ended: true,
                //     // id: 4,
                //     // latitude: 26,
                //     // longitude: 119,
                //     // type: 3,
                //     // updateTime: "2021-06-18 10:25:48",
                //     // updateUser: 2
                // }
                while(this.taskTotal > (curPage-1)*10) {
                    await viewTaskForTeacher(curPage ,10 ,courseId).then(res => {
                        // console.log(res);
                        if(res.data.code === 0) {
                            this.taskTotal = res.data.data.total;
                            for(let r of res.data.data.records) {                            
                                if(!r.ended) { // 如果课程没结束
                                    console.log('有课程没结束👇');
                                    console.log(r);
                                    this.taskInfo = r;
                                    break;
                                }
                            }                        
                        } else {
                            this.taskTotal = 0;
                        }
                    }).catch(err => console.log(err));
                    curPage++;
                }
                
            }   
		}
	}
</script>

<style>
    .bottom-button {
                    width: 160px;
                    height: 40px;
                }
</style>